# encoding: utf-8
"""
@Author: xiaxin
@ModuleName: timeit
@Time: 2020/3/4 
@Desc:
"""

# 实现一个timeit的装饰器：timeit 装饰能够计算被装饰函数的运行时间

import datetime, time
from functools import wraps


# 类实现
class Timeit:
    def __init__(self, fn):
        """
        this is time it
        """
        self.fn = fn
        wraps(fn)(self)

    def __call__(self, *args, **kwargs):
        self.start = datetime.datetime.now()
        ret = self.fn(*args, **kwargs)
        delta = (datetime.datetime.now() - self.start).total_seconds()
        print(f"{self.fn.__name__} function took {delta}s.")

        return ret


# 函数实现
def timeit(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        start = datetime.datetime.now()
        ret = fn(*args, **kwargs)
        delta = (datetime.datetime.now() - start).total_seconds()
        print(f"{fn.__name__} function took {delta}s.")

        return ret

    return wrapper


@Timeit
# @timeit
def add(x, y):
    """
    this is add
    """
    time.sleep(3)
    return x + y


if __name__ == '__main__':
    print(add.__doc__)
    add(3, 4)
